<?php
include 'includes/db.php';
session_start();

// 定义固定 token（如果需要）
define('FIXED_TOKEN', '6bphewrz2a30');

// 检查用户是否登录
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '用户未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$cost = 0; // 设置为0表示免费

// 获取用户余额
$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    echo json_encode(['success' => false, 'message' => '用户不存在']);
    exit;
}

// 检查余额是否足够
if ($user['balance'] < $cost) {
    echo json_encode(['success' => false, 'message' => '余额不足']);
    exit;
}

// 获取视频URL参数
$videoUrl = $_GET['url'] ?? '';

if (empty($videoUrl)) {
    echo json_encode(['success' => false, 'message' => '未提供短视频链接']);
    exit;
}

// 验证URL格式
if (!filter_var($videoUrl, FILTER_VALIDATE_URL)) {
    echo json_encode(['success' => false, 'message' => '无效的URL格式']);
    exit;
}

// 检查URL是否支持的平台
$parsedUrl = parse_url($videoUrl);
$host = strtolower($parsedUrl['host'] ?? '');
$supportedPlatforms = ['douyin', 'xiaohongshu', 'kuaishou', 'pipix', 'xiaochuankeji','xhslink', 'pipigx', 'weishi'];
$isSupported = false;

foreach ($supportedPlatforms as $platform) {
    if (strpos($host, $platform) !== false) {
        $isSupported = true;
        break;
    }
}

if (!$isSupported) {
    echo json_encode(['success' => false, 'message' => '不支持的平台，仅支持抖音、小红书、快手、皮皮虾、最右、皮皮搞笑和微视']);
    exit;
}

// 扣除费用（如果cost不为0）
if ($cost > 0) {
    $new_balance = $user['balance'] - $cost;
    $stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
    $stmt->execute([$new_balance, $user_id]);
}

// Flask应用API地址
$host = "http://113.47.13.136:4554/jx";
$method = "GET";
$url = $host . "?id=" . urlencode($videoUrl);

// 初始化cURL
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => $method,
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_TIMEOUT => 60, // 设置超时时间
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . FIXED_TOKEN, // 如果需要token验证
        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    ]
]);

// 执行请求
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);

// 检查cURL错误
if (!empty($error)) {
    echo json_encode(['success' => false, 'message' => '请求失败: ' . $error]);
    exit;
}

// 检查HTTP状态码
if ($httpCode !== 200) {
    echo json_encode(['success' => false, 'message' => 'API服务异常，状态码: ' . $httpCode]);
    exit;
}

// 解析响应
$result = json_decode($response, true);

// 检查JSON解析是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode(['success' => false, 'message' => '响应解析失败: ' . json_last_error_msg()]);
    exit;
}

// 检查Flask应用返回的错误
if (!$result['success']) {
    $errorMsg = $result['error'] ?? '未知错误';
    echo json_encode(['success' => false, 'message' => '解析失败: ' . $errorMsg]);
    exit;
}

// 调试：输出原始数据查看结构
// error_log("原始返回数据: " . print_r($result, true));

// 适配返回格式 - 修复数据结构
$mediaType = $result['media_type'] ?? '';
$items = $result['items'] ?? [];
$title = $result['title'] ?? '';
$author = $result['author'] ?? ['nickname' => '未知作者', 'avatar' => ''];
$coverUrl = $result['cover_url'] ?? '';

// 确保author是对象格式
if (is_string($author)) {
    $author = ['nickname' => $author, 'avatar' => ''];
}

// 根据media_type设置type字段
if ($mediaType === 'video') {
    $type = 1;
    $videoUrl = $items[0]['url'] ?? '';
    $pics = [];
} elseif ($mediaType === 'image') {
    $type = 2;
    $videoUrl = '';
    $pics = array_map(function($item) {
        return $item['url'] ?? '';
    }, $items);
} elseif ($mediaType === 'mixed') {
    $type = 3; // 混合类型
    $videoUrl = '';
    $pics = [];
    
    // 提取所有媒体资源
    foreach ($items as $item) {
        if (($item['type'] ?? '') === 'video') {
            $videoUrl = $item['url'] ?? '';
        } else {
            $pics[] = $item['url'] ?? '';
        }
    }
} else {
    echo json_encode(['success' => false, 'message' => '未知的媒体类型: ' . $mediaType]);
    exit;
}

// 返回成功结果 - 确保数据结构正确
$responseData = [
    'success' => true, 
    'data' => [
        'type' => $type,
        'video_url' => $videoUrl,
        'pics' => $pics,
        'title' => $title,
        'author' => $author, // 确保这是对象
        'cover_url' => $coverUrl,
        'media_type' => $mediaType,
        'items' => $items
    ],
    'balance' => ($cost > 0) ? $new_balance : $user['balance'] // 返回更新后的余额
];

// 调试：输出最终返回的数据结构
// error_log("最终返回数据: " . print_r($responseData, true));

echo json_encode($responseData);
?>